package com.gomyb.admin.module.product.service.impl;

import com.gomyb.admin.module.product.dao.AppProductRepertoryDao;
import com.gomyb.admin.module.product.model.AppProductRepertory;
import com.gomyb.admin.module.product.service.AppProductRepertoryService;
import com.gomyb.common.base.BaseDao;
import com.gomyb.common.base.BaseServiceImpl;
import com.gomyb.common.page.PageParam;
import com.gomyb.common.page.PageResult;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.transaction.Transactional;
import java.math.BigDecimal;
import java.util.Map;

/**
 * @author <a href="mailto:hellohesir@gmail.com">Mr_He</a>
 * 2019/3/14 10:37
 */
@Service
public class AppProductRepertoryServiceImpl extends BaseServiceImpl<AppProductRepertory, Long> implements AppProductRepertoryService {

    @Override
    @Autowired
    public void setDao(BaseDao<AppProductRepertory, Long> dao) {
        super.dao = dao;
    }

    @Override
    public PageResult<com.gomyb.admin.module.product.model.pojo.AppProductRepertory> findPageBySql(PageParam pageParam) {
        //language=SQL
        StringBuilder sql = new StringBuilder("SELECT\n" +
                "  t3.id,\n" +
                "  t1.id productId,\n" +
                "  t1.category_id categoryId,\n" +
                "  t3.count,\n" +
                "  t1.each_count eachCount,\n" +
                "  t1. NAME productName,\n" +
                "  t1.model\n" +
                "FROM\n" +
                "  app_product t1\n" +
                "    LEFT JOIN app_product_repertory t3 ON t1.id = t3.product_id WHERE 1=1");
        Map<String, String> data = pageParam.getData();
        if (data.size() > 0) {
            if (StringUtils.isNotEmpty(data.get("name"))) {
                sql.append(" and t1.name like '%").append(data.get("name")).append("%' ");
            }
            if (StringUtils.isNotEmpty(data.get("categoryId"))) {
                sql.append(" and t1.category_id = ").append(data.get("categoryId"));
            }
        }
        return super.findPageBySql(sql.toString(), pageParam, com.gomyb.admin.module.product.model.pojo.AppProductRepertory.class);
    }

    @Transactional
    @Override
    public boolean updateCount(BigDecimal count, BigDecimal oldCount, Long id) {
        try {
            int num = ((AppProductRepertoryDao) dao).updateCount(count, oldCount, id);
            return num > 0;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return false;
    }

}
